
var Producthtml = "";//产品的html存放

var goodsList = JSON.parse(localStorage.getItem("goodsList"));//价格合计
createOrder(goodsList, function() {})//订单信息渲染

$('.add_address').on( 'tap', function() {
	//跳转到地址页面
	window.location.href = "addressList.html?type=order";//跳转到地址页面.并且带上type=order (固定) 表明是从订单页面过来的.
});

/*收货地址加载*/
if(localStorage.orderMsg && localStorage.orderMsg !='') {
	//	如果已经选中地址
	//需要处理如果选中地址被删除
	var curOrderMsg = JSON.parse(localStorage.orderMsg);
	$(".add_address").empty();
	var addresshtml = "";
	addresshtml += '<div class="A-top">' +
		' <div class="A-name">收货人：<b id="realname">' + curOrderMsg.name + '</b><span id="pmobile">' + curOrderMsg.phone + '</span></div> ' +
		'<div class="A-address">收货地址：<span id="address">' + curOrderMsg.address + '</span></div> <input type="hidden" id="zip">' +
		'</div>'

	$(".add_address").append(addresshtml);
} else {
	//默认加载地址里面第一条
	MuiAjaxFn('client/delivery/address/selectbyuserid', '{}', function(data) {
		var addresshtml = ""
//		console.log(data.dataResultList.length )
		if(data.dataResultList.length == 0) {
			//用户没有添加地址
			addresshtml += '添加地址<span class="mui-icon mui-icon-plusempty"></span>';
		} else {
			var curOrderMsg = data.dataResultList[0];
			addresshtml += '<div class="A-top">' +
				'<div class="A-name">收货人：<b id="realname">' + curOrderMsg.consignee + '</b><span id="pmobile">' + curOrderMsg.mobile + '</span></div> ' +
				'<div class="A-address">收货地址：<span id="address">' + curOrderMsg.province + '' + curOrderMsg.city + '' + curOrderMsg.county + '' + curOrderMsg.detailedAddress + '</span></div> <input type="hidden" id="zip">' +
				'</div>'
		}

		$(".add_address").append(addresshtml);
	})
}

// }
/*订单商品信息渲染*/
function createOrder(goodsList, callback) {

	for(var i = 0; i < goodsList.length; i++) {
		var countPriceElem = mui(".span_pj_num")[0]; //总价元素
		var goodsItemCount = goodsList[i].count;
		var goodsAllCount = goodsList[i].allcount;
		var goodsAllPrice = goodsList[i].allprice;

		$(".numprice .num").html(goodsAllCount)
		$(".list_number .fright").html(goodsAllCount);
		console.log(goodsList)

		// var goodsItemPriceSum += goodsItemCount;
		// console.log(goodsItemPriceSum)
		var goodsItemCommodityNumber = goodsList[i].commodityNumber;
		(function(goodsItemCommodityNumber, goodsItemCount) { //闭包，相对全局的变量不要放进这里

			AjaxLGettFn("api/bizcommodity/selectbynumber?adcode=100000&commoditynumber=" + goodsItemCommodityNumber, function(data) {
				// console.log(JSON.stringify(data));

				// if(goodsList[i].price!=undefined){
				//          	var goodsItemPrice = goodsList[i].price;
				//          }else{
				var goodsItemPrice = (data.dataResultObj.dataResultObj.originalPrice) / 100;
				var presentPrice = (data.dataResultObj.dataResultObj.presentPrice) / 100;
				var thisdata = data.dataResultObj.dataResultObj;
				// }

				//		console.log(data)
				//服务器返回响应，根据响应结果，分析是否登录成功；
				$(".detalist").empty()
				Producthtml += '<div class="detail_top orderli clearfix" data-cNum="' + thisdata.commodityNumber + '" data-count="' + goodsItemCount + '">' +
					'<div class="details_img mui-col-xs-4" style="background-image:url(' + IMGUrl + '' + data.dataResultObj.mainPhoto + ')">' +
					'</div>' +
					'<div class="details_text mui-col-xs-8">' +
					'<p><span class="name">' + data.dataResultObj.title + ' </span><span class="price">￥' + presentPrice + '</span></p>' +
					'<p class="clearfix"><span style="text-decoration:line-through;">￥' + goodsItemPrice + '</span></p>' +
					'<p class="count"><span>x' + goodsItemCount + '</span></p>' +
					'<span class="white mark">官方配送</span>' +
					'</div>' +
					'</div>'
				$(".detalist").append(Producthtml)
				var ssjj = ($(".count span").html()).substring(1) * ($(".price").html()).substring(1)

				//		console.log(data)
				if(goodsAllPrice) {
					$(".Allprice").html("￥" + goodsAllPrice)
				} else {
					$(".Allprice").html("￥" + ssjj)
				}
				// $(".list-wrapper").empty();
			})

		})(goodsItemCommodityNumber, goodsItemCount);
	}
}

function SubmitOrder(topay) {
	//确认提交订单
	//	if(topay== "Wechat"){
	var orderlist = '';
	$.each($(".orderli"), function(idx, obj) {
		//点击提交订单需要去掉该商品在购物车的位置
		MuiAjaxFn("client/detailed/deletebycommodity", {
			'commodityNumber':$(".orderli").eq(idx).attr("data-cNum")
		}, function(data) {
			if(data.htmlState.status == 200) {
//				mui.toast("删除商品成功");
//				totalFn() 
			} else {
				//	删除商品失败的处理
			}
		})
		
		//		console.log($(".orderli").eq(idx).attr("data-cNum"))
		orderlist += '{commodityNumber:' + $(".orderli").eq(idx).attr("data-cNum") + ',buyAmount:' + $(".orderli").eq(idx).attr("data-count") + '}';
	})
		//	console.log("orderlist:"+orderlist)
		
	var thisorderMsg = JSON.stringify(localStorage.orderMsg);
	$.ajax({
		type: "post",
		contentType: "application/json", //必须有
		url: URL_all + 'client/orderinfo/generateorder',
		headers: {
			'userToken': localStorage.userToken
		},
		data: "{'orderinfo':{'orderAddress':'" + $("#address").text() + "', 'contactName':'"+$("#realname").text()+"', 'contactPhone':'"+$("#pmobile").text()+"', 'paymentMethod':'Wechat','orderAdcode':'100000','':'"+$(".talkinput").val()+"'}," +
			"'commodity':[" + orderlist + "]," +
			"'incidental':[]}",
		success: function(data) {

			if(typeof WeixinJSBridge == "undefined") {
				if(document.addEventListener) {
					document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
				} else if(document.attachEvent) {
					document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
					document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
				}
			} else {
				onBridgeReady(data);

			}
		},
		error: function(xhr, type, errorThrown) {
			//异常处理；
			console.log(type);
		}
	});
	

}
function onBridgeReady(data) {
	//	console.log(JSON.parse(data))
	//	var data = JSON.parse(data);
	// console.log(data)
	WeixinJSBridge.invoke(
		'getBrandWCPayRequest', {
			"appId": data.dataResultObj.dataResultObj.appId, //公众号名称，由商户传入     
			"timeStamp": data.dataResultObj.dataResultObj.timeStamp, //时间戳，自1970年以来的秒数     
			"nonceStr": data.dataResultObj.dataResultObj.nonceStr, //随机串     
			"package": data.dataResultObj.dataResultObj.prepayId,
			"signType": "MD5", //微信签名方式：     
			"paySign": data.dataResultObj.dataResultObj.paySign //微信签名 
		},
		function(res) {
			console.log(res)
			if(res.err_msg == "get_brand_wcpay_request:ok") {
				mui.toast("支付成功");
				nodata('支付成功', 'body', 0);
				
				
			} else if(res.err_msg == "get_brand_wcpay_request:cancel") {
				mui.toast("已取消支付");
				nodata('已取消支付', 'body', 0);
			} // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回    ok，但并不保证它绝对可靠。 
		}

	);
}

window.onload = function() {
	mui('body').on('tap', '#affirm', function() {
		if($(".A-top").length > 0){
			SubmitOrder();
		}else{
			//用户没有录入地址信息
			mui.toast("亲,您还没有选择地址哦!");
		}
		
	});
}

//
//$(window).bind('beforeunload', function(){ 
//	console.log("进行了一次刷新")
//  return false; 
//});


